<template>
  <div>
    <el-container  style="flex-wrap: wrap;">
      <!-- 头部导航栏 -->
      <BreadHeader></BreadHeader>
      <el-main>
        <XPannel>
          <template v-slot:header>
            <span>个人信息修改</span>
          </template>
          <template v-slot:default>
            <div class="content_two">
              <!-- 显示当前用户基本信息 -->
              <!-- <el-form
                ref="infoForm"
                :model="infoForm"
                :rules="rules"
                label-width="100px"
                style="width: 300px"
              >
                <el-form-item label="当前名称：">
                  <span>{{ obtain_name }}</span>
                </el-form-item>
                <el-form-item label="当前账号：">
                  <span>{{ obtain_account }}</span>
                </el-form-item>
                <el-form-item label="当前密码：">
                  <span>{{ obtain_password }}</span>
                </el-form-item>
                <el-form-item label="当前部门：">
                  <span>{{ obtain_partname }}</span>
                </el-form-item>
                <el-form-item label="当前头像：">
                  <img
                    src="../assets/MBH-3.jpg"
                    alt=""
                    width="150px"
                    height="170px"
                  />
                </el-form-item>
              </el-form> -->
              <el-form
                ref="infoForm"
                :model="infoForm"
                :rules="rules"
                label-width="100px"
                style="width: 400px;margin: auto"
              >
                <el-form-item label="修改名称：" prop="username">
                  <el-input
                    v-model="infoForm.username"
                    placeholder="请输入您要修改的用户名"
                  ></el-input>
                </el-form-item>

                <el-form-item label="修改账号：" prop="phone">
                  <el-input
                    v-model="infoForm.phone"
                    placeholder="请输入您要修改的账号"
                  ></el-input>
                </el-form-item>

                <el-form-item label="修改密码：" prop="password">
                  <el-input
                    type="password"
                    v-model="infoForm.password"
                    placeholder="请输入您要修改的密码"
                    show-password
                  ></el-input>
                </el-form-item>

                <el-form-item label="修改部门：">
                  <el-input
                    placeholder="您没有权限修改所处部门"
                    :disabled="true"
                  ></el-input>
                </el-form-item>
                <!--  -->
                <el-form-item label="头像上传：" prop="avatar">
                  <el-upload
                    class="avatar-uploader"
                    name="picture"
                    action="http://127.0.0.1:3000/baoxiu/upload"
                    :show-file-list="true"
                    :headers="uploadHeaders"
                    :on-error="handleUploadError"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('infoForm')"
                    >保存修改</el-button
                  >
                  <el-button @click="resetForm('infoForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </template>
        </XPannel>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import XPannel from "@/components/XPannel.vue";
import http from "@/api/http";
import BreadHeader from "@/components/BreadHeader.vue";

export default {
  components: {
    XPannel,
    BreadHeader
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      const pattern = /^1[3456789]\d{9}$/;
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else if (!pattern.test(value)) {
        return callback(new Error("请输入正确格式的手机号"));
      } else {
        return callback();
      }
    };
    return {
      uploadHeaders: {
        'Authorization': '' // 这里将用于存放Token
      },
      infoForm: {
        username: "",
        phone: "",
        password: "",
        avatar: "", // 用于存储上传后的头像URL
      },
      rules: {
        username: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" },
        ],
        phone: [{ validator: validatePhone, trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
        ],
      },
      imageUrl: "",
      // 修改获取的信息
      obtain_id: null,
      obtain_name: "",
      obtain_account: "",
      obtain_password: "",
      obtain_partname: "",
    };
  },
  methods: {
    handleUploadError(res){
      console.log("err:",res)
    },
    // 图片上传的一系列操作
    handleAvatarSuccess(res, file) {
      console.log("上传完成:",res)
      console.log(file)
      let url = res.data.fileName
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = `http://localhost:3000${url}`;

    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 确认保存页面
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.save_info();
          
        } else {
          console.log("个人信息修改失败!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 信息修改---保存--接口
    save_info() {
      http
        .post("/renyuan/save_edit/" + this.obtain_id, {
          uname: this.infoForm.username,
          mobile: this.infoForm.phone,
          pwd: this.infoForm.password,
          picture:this.imageUrl
        })
        .then((response) => {
          console.log(response);
          this.$message({
            message: "恭喜你，个人信息修改成功！",
            type: "success",
          });
        })
        .catch((error) => {
          console.error(error); // 使用console.error来打印错误
        });
    },
    // 个人信息修改--获取信息
    // 个人信息修改--获取信息
    obtain_info() {
      const account = localStorage.getItem("account");
      http
        .get("/renyuan/edit_person/" + account)
        .then((response) => {
          console.log(response);
          this.obtain_id = response.data[0].id;
          this.obtain_name = response.data[0].uname;
          this.obtain_account = response.data[0].account;
          this.obtain_password = response.data[0].pwd;
          this.obtain_partname = response.data[0].pname;
          this.imageUrl = response.data[0].picture;

          this.infoForm.username = response.data[0].uname;
          this.infoForm.phone = response.data[0].account;
          this.infoForm.password = response.data[0].pwd;
          this.obtain_partname = response.data[0].pname;
          // 在这里调用login_name方法，确保数据已经获取
          this.login_name();
          this.picture_url();
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    },
    // 个人信息:this.obtain_name--姓名存到vuex中,方便其他组件使用
    login_name() {
      // 将数据提交到Vuex
      if (this.obtain_name) {
        // 将数据提交到Vuex
        this.$store.dispatch("setUserNameAction", this.obtain_name);
      } else {
        console.error("Vuex 出错");
      }
    },
    picture_url(){
      if (this.imageUrl) {
        // 将数据提交到Vuex
        this.$store.dispatch("setUserPictureAction", this.imageUrl);
      } else {
        console.error("Vuex 出错");
      }
    }
    // 信息修改---保存--接口
  },
  created() {
    this.obtain_info();
  },
  mounted(){
     // 假设Token存储在localStorage中
     this.uploadHeaders['Authorization'] = `${localStorage.getItem('token')}`;
    //  this.uploadHeaders['Authorization'] = ``;
  }
};
</script>


<style scoped>
.el-card__body,
.el-main {
  padding: 0px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.content_two {
  width: 750px;
  display: flex;
  margin: auto;
  justify-content: space-between;
}
</style>
